package handler

import (
	"github.com/gin-gonic/gin"
	"merge-master/cahce"
	"merge-master/model"
	"merge-master/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不能为空",
		})
		return
	}
	redis_key := "redis_login" + username
	js, _ := cahce.Rdb.Get(cahce.Ctx, redis_key).Int()
	if js >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误，禁止登录",
		})
		return
	}
	var user model.User
	model.DB.Where("username = ?", username).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cahce.Rdb.Incr(cahce.Ctx, redis_key)
		if js == 2 {
			cahce.Rdb.Set(cahce.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 400,
		"msg":  "登录成功",
	})
	return
}
